<?php
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/




/**
 * @name KeepSearches
 * @copyright 2008  MP2P Technologies S.A.
 * @abstract MediaWiki Extension to keeps into a database all the query searches made by users
 * 
 */

if ( ! defined( 'MEDIAWIKI' ) )
die();

require_once("DatabaseFunctions.php");

#install extension hook
$wgExtensionFunctions[] = "wfKeepSearchesExtension";

#extension hook callback function
function wfKeepSearchesExtension() {
  global $wgRequest, $wgDBprefix, $wgOut;

  if($wgRequest->getText( 'title' ) == 'Special:Search' ) { //just fetch query search on the search page

    $search = trim($wgRequest->getText( 'search' ));
    $datenow = date("Y-m-d H:i:s", time() );

    if ($search != '' ) {


      $dbr = wfGetDB( DB_SLAVE );
      $search = strtolower(mysql_real_escape_string($search));


      $sql = "SELECT ks_id, ks_query_search, ks_date, ks_count
            FROM {$wgDBprefix}keep_searches WHERE ks_query_search = '$search'";

      $res = $dbr->query( $sql );


      if ( $row = $dbr->fetchObject( $res ) ) { // if the query exists in ddbb update the counter +1

        //$wgOut-> 'row='.print_r($row);

        $count = $row->ks_count+1;

        $dbr->freeResult( $res );

        $dbw = wfGetDB( DB_MASTER );
        $dbw->update( 'keep_searches',
        array( /* SET */
        'ks_count' => $count,
        'ks_date' => $datenow,
        ), array( /* WHERE */
        'ks_query_search' => $search
        ), ""
        );



      } else { //if not exists the query search, create new row

        $dbw =& wfGetDB( DB_MASTER );
        $dbw->begin();
        $sql = "INSERT INTO {$wgDBprefix}keep_searches (ks_query_search, ks_date, ks_count)
            VALUES ('$search' , '$datenow', '1')";

        $dbw->query( $sql );
        $dbw->commit();
      }

    }


  }

}


/**
 * @name generateTagCloudSearches
 * @abstract renders a tag cloud based on the count of TOP count popular searches
 * @param $SIZE_LIST
 * @param $SIZE_OFFSET
 */

function generateTagCloudSearches ( $SIZE_LIST, $SIZE_OFFSET ){
  global $wgDBprefix, $wgScriptPath, $wgOut;
  $args = func_get_args();


  if ($args[0] == null) { //if $SIZE_LIST its not passed set by default
    $SIZE_LIST = 20;  //top 10, or top 20, etc...

  }

  if ($args[1] == null) { //if $SIZE_OFFSET its not passed set by default
    $SIZE_OFFSET = 0; //the number of the row where we start to fetch rows
  }


  $dbr = wfGetDB( DB_SLAVE );
  $sql = "SELECT DISTINCT ks_id, ks_query_search, ks_date, ks_count
            FROM {$wgDBprefix}keep_searches  ORDER BY ks_count DESC LIMIT {$SIZE_LIST} OFFSET {$SIZE_OFFSET}";

  $res = $dbr->query( $sql );


  //insert tags in array from database
  while ($row = $dbr->fetchObject( $res )) {


    //check if ss_nameize function exist, only useful if you are installing extension out of soundshare code
    if (function_exists('ss_nameize')) {
      $row->ks_query_search = ss_nameize($row->ks_query_search);
    }

    $tags[] = $row->ks_query_search.'@'.$row->ks_count;



  }
  $dbr->freeResult ( $res );


  sort($tags);

  $out .= '<div class="tagcloud"><ul>';

  // Increasing this number will make the words bigger; Decreasing will do reverse
  $factor = 0.5;
  // Smallest font size possible
  $starting_font_size = 8;
  $max_count = 1000;


  //check the $ssSearchPath
  if (!function_exists('ss_nameize')) { //if you are using this extension without soundshare code, you can change the $ssSearchPath value

    $ssSearchPath = $wgScriptPath.'/Special:Search?search=';
  } else {

    $ssSearchPath = '/search/';
  }


  foreach ($tags as $key => $value)
  {

    $values = explode("@", $value);
    $x = round(($values[1] * 110) / $max_count) * $factor;

    //fix the max
    if ($x > 18) {
      $x = 18;
    }

    $font_size = $starting_font_size + $x.'px';

    //check if ss_nameize function exist, only useful if you are installing extension out of soundshare code
    if (function_exists('ss_nameize')) {


      $row->ks_query_search = ss_nameize($row->ks_query_search);
    }


    $query_search = str_replace(' ', ' <wbr />',$values[0]);
    $out .= ' <li><a class="tag" style="font-size: '.$font_size.'" title="'.$values[0].'" href="'.$ssSearchPath.$values[0].'">'.$query_search."<wbr /></a></li> ";

  }


  $out .= '</ul></div>';

  echo $out;


}

///////////////////////////////////////////////////////////////////////////////////end

$wgExtensionCredits['parserhook'][] = array(
'name' => 'Keep Searches',
'author' =>'MP2P Technologies S.A.',
'url' => 'http://www.mediawiki.org/wiki/Extension:KeepSearches',
'version' => '1.0',
'description' => 'This extension keeps in database and counts all the queries done on the searchbox for stats purposes'
);

